<template>
  <div>
    <pro-table
      ref="tableRef"
      :data="tableData"
      :total="total"
      :columns="columns"
      :tool-button="false"
      @search="commEvent.onSearch"
      @reset="commEvent.onReset"
      :page-change="commEvent.onPageChange"
    >
      <!-- 顶部配置项 -->
      <template #tableHeader>
        <el-row justify="end">
          <el-button type="primary" icon="Download" @click="commEvent.onExport()" :loading="exportLoading">导出</el-button>
        </el-row>
      </template>
    </pro-table>
  </div>
</template>

<script setup lang="ts">
import { h, onMounted, ref } from "vue"
import { ElMessage } from "element-plus"
import ProTable from "@/components/ProTable/index.vue"
import { ColumnProps, EnumProps, ProTableInstance } from "@/components/ProTable/interface"
import { getLinePageQuery } from "@/api/modules/efficiency"
import { organByLevel } from "@/api/modules/system"
import { SystemSpace } from "@/api/interface/efficiency"
import { useUserStore } from "@/stores/modules/user"

// 获取当前日期
const getCurrentDate = () => {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, "0")
  const day = String(today.getDate()).padStart(2, "0")
  return `${year}-${month}-${day}`
}
// 参数
const tableRef = ref<ProTableInstance>() // 表格实例
const tableData = ref<SystemSpace.LinePage[]>([]) // 表格数据
const total = ref<number>(0) // 数据总数
const exportLoading = ref<boolean>(false) // 导出加载状态
const factoryEnum = ref<EnumProps[]>([]) // 厂区
const lineEnum = ref<EnumProps[]>([]) // 产线
// const deviceTypeEnum = ref<EnumProps[]>([]) // 设备类型
// 页码参数
const pageParams = ref({
  pageIndex: 1,
  pageSize: 10
})
// 表格列配置
const columns: ColumnProps<SystemSpace.LinePage>[] = [
  {
    prop: "sort",
    label: "序号",
    width: 80,
    render: scope => h("span", scope.$index + 1 + (pageParams.value.pageIndex - 1) * pageParams.value.pageSize)
  },
  { prop: "lineId", label: "产线名称", enum: lineEnum },
  {
    prop: "cleanA",
    label: "A清",
    render: (scope: any) => {
      const cnt = scope.row.cleanACnt || 0
      const times = scope.row.cleanATimes || 0
      return `${cnt}次/${times}小时`
    }
  },
  {
    prop: "cleanB",
    label: "B清",
    render: (scope: any) => {
      const cnt = scope.row.cleanBCnt || 0
      const times = scope.row.cleanBTimes || 0
      return `${cnt}次/${times}小时`
    }
  },
  {
    prop: "cleanC",
    label: "C清",
    render: (scope: any) => {
      const cnt = scope.row.cleanCCnt || 0
      const times = scope.row.cleanCTimes || 0
      return `${cnt}次/${times}小时`
    }
  },
  {
    prop: "dateRange",
    label: "计划停机时间",
    search: {
      el: "date-picker",
      props: {
        type: "daterange",
        format: "YYYY-MM-DD",
        valueFormat: "YYYY-MM-DD",
        rangeSeparator: "至",
        startPlaceholder: "开始日期",
        endPlaceholder: "结束日期"
      },
      defaultValue: [getCurrentDate(), getCurrentDate()]
    }
  },
  {
    prop: "startRate",
    label: "开动率"
  }
]
// 事件集合
const commEvent = {
  // 导出数据（参考Vue2成功示例改写为Vue3）
  onExport: async () => {
    try {
      exportLoading.value = true

      // 获取当前搜索参数
      const _search = tableRef.value?.searchParam || {}

      // 处理日期范围参数（对应Vue2的this.queryParams）
      const queryParams: any = { ...pageParams.value, ..._search }
      if (queryParams.dateRange && Array.isArray(queryParams.dateRange) && queryParams.dateRange.length === 2) {
        queryParams.startDay = queryParams.dateRange[0]
        queryParams.endDay = queryParams.dateRange[1]
        delete queryParams.dateRange
      }

      console.log("导出参数：", queryParams)

      // 使用原生fetch完全绕过axios拦截器
      const baseURL = import.meta.env.VITE_API_URL
      const userStore = useUserStore()

      // 构建完整URL
      const queryString = Object.keys(queryParams)
        .filter(key => queryParams[key] !== undefined && queryParams[key] !== null && queryParams[key] !== "")
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`)
        .join("&")

      const fullUrl = `${baseURL}/stat/line/export?${queryString}`
      console.log("完整URL：", fullUrl)

      const response = await fetch(fullUrl, {
        method: "GET",
        headers: {
          token: userStore.token
        }
      })

      console.log("fetch响应：", response)

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const content = await response.blob()
      console.log("blob内容：", content)

      console.log("最终内容：", content)
      // 创建带正确MIME类型的Blob，解决乱码问题
      const blob = new Blob([content], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      })
      const fileName = new Date().getTime() + ".xlsx"

      if ("download" in document.createElement("a")) {
        // 非IE下载
        const elink = document.createElement("a")
        elink.download = fileName
        elink.style.display = "none"
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        ;(navigator as any).msSaveBlob(blob, fileName)
      }

      ElMessage.success("导出成功")
    } catch (error) {
      console.error("导出失败：", error)
      ElMessage.error("导出失败，请重试")
    } finally {
      exportLoading.value = false
    }
  },
  // 获取所属厂区
  getFactory: async () => {
    const { data } = await organByLevel(1)
    factoryEnum.value = data.map(item => ({
      label: item.organName,
      value: item.id
    }))
  },
  // 获取所属产线
  getLine: async () => {
    const { data } = await organByLevel(2)
    lineEnum.value = data.map(item => ({
      label: item.organName,
      value: item.id
    }))
  },
  // 获取表格数据
  getTableData: async (params: SystemSpace.LinePageQuery) => {
    // 处理日期范围参数
    const queryParams = { ...params }
    if (params.dateRange && Array.isArray(params.dateRange) && params.dateRange.length === 2) {
      queryParams.startDay = params.dateRange[0]
      queryParams.endDay = params.dateRange[1]
      delete queryParams.dateRange
    }

    const { data } = await getLinePageQuery(queryParams)
    tableData.value = data.result || []
    total.value = data.totalCount
  },
  // 查询
  onSearch: () => {
    tableRef.value?.search()
    pageParams.value.pageIndex = 1
    const _search = tableRef.value?.searchParam
    commEvent.getTableData({ ...pageParams.value, ..._search })
  },
  // 重置
  onReset: () => {
    // 重置页码
    pageParams.value.pageIndex = 1
    pageParams.value.pageSize = 10

    // 确保表格搜索表单也被重置
    tableRef.value?.reset()

    // 重置为默认参数（当天日期）
    const defaultParams = {
      ...pageParams.value,
      startDay: getCurrentDate(),
      endDay: getCurrentDate()
    }

    // 重新加载数据
    commEvent.getTableData(defaultParams)
  },
  // 分页
  onPageChange: (page: number, size: number) => {
    pageParams.value.pageIndex = page
    pageParams.value.pageSize = size
    const _search = tableRef.value?.searchParam
    commEvent.getTableData({ ...pageParams.value, ..._search })
  }
}
onMounted(() => {
  // 设置默认日期筛选为当天
  const defaultParams = {
    ...pageParams.value,
    startDay: getCurrentDate(),
    endDay: getCurrentDate()
  }
  commEvent.getTableData(defaultParams)
  commEvent.getFactory()
  commEvent.getLine()
})
</script>
